import './index.less';
import './base.less';
import { useMemo } from 'react';

type SideMenuConfigT = {
  icon: (active: boolean) => JSX.Element;
  key: string | number;
  name: string;
  count: null | number;
};

interface ISideMenuProps {
  config: SideMenuConfigT[];
  activeKey: string | number;
  onSelect: (key: string | number) => void;
  customComponent?: JSX.Element;
}

interface ISideMenuItemProps {
  name: string;
  count: number;
  active: boolean;
  icon?: JSX.Element;
  onClick: () => void;
}

const SideMenuItem = (props: ISideMenuItemProps) => {
  const { name, count, icon, onClick, active } = props;
  return (
    <button
      className={`menu-item ${active ? 'menu-item--active' : ''}`}
      onClick={onClick}
      title={name}
    >
      {icon}
      <label className="menu-item__name">{name}</label>
      {count > 0 && <span className="menu-item__count">{count}</span>}
    </button>
  );
};

const SideMenu = (props: ISideMenuProps) => {
  const { config, activeKey, onSelect, customComponent } = props;

  const activeIndex = useMemo(() => {
    const activeItem = config.find((i) => i.key === activeKey);
    if (!activeItem) {
      return 0;
    }
    return config.indexOf(activeItem);
  }, [activeKey, config]);

  return (
    <>
      <div className="main-menu">
        <div
          className="logo"
          onClick={() => {
            window.location.reload();
          }}
        ></div>
        <div className="main-menu__content">
          {config.map((i) => (
            <SideMenuItem
              name={i.name}
              active={activeKey === i.key}
              key={i.key}
              onClick={() => onSelect(i.key)}
              count={i.count || 0}
              icon={i.icon(activeKey === i.key)}
            />
          ))}
          <div
            className="main-menu__indicator"
            style={{ transform: `translateY(${activeIndex * 60}px)` }}
          ></div>
        </div>
        {customComponent}
      </div>
    </>
  );
};

export default SideMenu;
